<template>
  <AdminLayout>
    <el-card class="course-list-card">
      <template #header>
        <div class="card-header">
          <h2>课程列表</h2>
          <el-button type="primary" @click="handleAddCourse">
            <el-icon><Plus /></el-icon>
            添加课程
          </el-button>
        </div>
      </template>

      <el-table :data="courseList" style="width: 100%">
        <el-table-column prop="courseId" label="课程ID" width="80" />
        <el-table-column prop="courseName" label="课程名称" width="180" />
        <el-table-column prop="courseCode" label="课程编码" width="120" />
        <el-table-column prop="credit" label="学分" width="100" />
        <el-table-column prop="description" label="课程描述">
          <template #default="{ row }">
            <el-tooltip :content="row.description" placement="top">
              <div class="description-text">{{ row.description || '-' }}</div>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180">
          <template #default="{ row }">
            {{ formatDateTime(row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="课程分配" width="200">
          <template #default="{ row }">
            <el-button
              v-if="row.courseAllocations && row.courseAllocations.length > 0"
              type="primary"
              link
              @click="showCourseAllocations(row)"
            >
              {{ row.courseAllocations.length }} 个分配
            </el-button>
            <span v-else>暂无分配</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleEditCourse(row)">
              <el-icon><Edit /></el-icon>
              编辑
            </el-button>
            <el-button type="danger" size="small" @click="handleDeleteCourse(row.courseId)">
              <el-icon><Delete /></el-icon>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 课程分配详情对话框 -->
    <el-dialog
      v-model="allocationDialogVisible"
      title="课程分配详情"
      width="60%"
      :close-on-click-modal="false"
    >
      <el-table :data="currentCourse?.courseAllocations || []" style="width: 100%">
        <el-table-column label="教师姓名" prop="teacherName" width="120" />
        <el-table-column label="班级" prop="className" width="100" />
        <el-table-column label="学期" prop="semester" width="100" />
      </el-table>
    </el-dialog>
  </AdminLayout>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter } from 'vue-router'
import { get, postJson } from '../../utils/api'
import { Plus, Edit, Delete } from '@element-plus/icons-vue'
import AdminLayout from '../../components/admin/AdminLayout.vue'

const router = useRouter()

// 课程列表数据
const courseList = ref<any[]>([])
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)

// 对话框状态
const allocationDialogVisible = ref(false)
const currentCourse = ref<any>(null)

// 加载课程列表
const loadCourseList = async () => {
  try {
    const result = await get('/course/query')
    if (result.code === 200) {
      courseList.value = result.data || []
      total.value = result.dataCount || 0
    } else {
      ElMessage.error('加载课程列表失败')
    }
  } catch (error) {
    console.error('加载课程列表错误:', error)
    ElMessage.error('网络错误，请检查后端服务')
  }
}

// 格式化日期时间
const formatDateTime = (dateTimeString: string) => {
  if (!dateTimeString) return ''
  const date = new Date(dateTimeString)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 处理添加课程
const handleAddCourse = () => {
  router.push('/admin/course/add')
}

// 处理编辑课程
const handleEditCourse = (course: any) => {
  // 这里可以跳转到编辑页面，并传递课程ID
  ElMessage.info('编辑功能开发中')
}

// 处理删除课程
const handleDeleteCourse = async (courseId: number) => {
  try {
    await ElMessageBox.confirm(
      '确定要删除该课程吗？删除后将不可恢复。',
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    const result = await get(`/course/delete?id=${courseId}`)
    if (result.code === 200) {
      ElMessage.success('删除成功')
      loadCourseList() // 重新加载列表
    } else {
      ElMessage.error(result.msg || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除课程错误:', error)
      ElMessage.error('操作失败')
    }
  }
}

// 显示课程分配详情
const showCourseAllocations = (course: any) => {
  currentCourse.value = course
  allocationDialogVisible.value = true
}

// 分页相关处理
const handleSizeChange = (size: number) => {
  pageSize.value = size
  loadCourseList()
}

const handleCurrentChange = (current: number) => {
  currentPage.value = current
  loadCourseList()
}

// 组件挂载时加载数据
onMounted(() => {
  loadCourseList()
})
</script>

<style scoped>
.course-list-card {
  margin: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  text-align: center;
  font-weight: bold;
  padding: 0;
}

.card-header h2 {
  margin: 0;
  font-size: 20px;
  font-weight: 500;
}

.description-text {
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
  line-clamp: 2;
  overflow: hidden;
  text-overflow: ellipsis;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

:deep(.el-table__fixed-right) {
  height: 100% !important;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .course-list-card {
    margin: 10px;
  }
  
  .card-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
  
  .pagination-container {
    justify-content: center;
  }
}
</style>